package com.umakr.ax.core.filter;



import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author gx
 */
public class CurrentHttpRequestFilter implements Filter {
    private static ThreadLocal<Pair<HttpServletRequest,HttpServletResponse>> currentHttp= new ThreadLocal<>();
    public static Pair<HttpServletRequest,HttpServletResponse> getCurrentHttp(){
        return currentHttp.get();
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Do nothing because of X and Y.
    }



    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        /*唐腾飞添加：解决跨域请求*/
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

        HttpServletRequest req = (HttpServletRequest)servletRequest;
        currentHttp.set(new Pair<HttpServletRequest,HttpServletResponse>(req, (HttpServletResponse) servletResponse));
        filterChain.doFilter(servletRequest, servletResponse);
        currentHttp.remove();
    }

    @Override
    public void destroy() {
        // Do nothing because of X and Y.
    }
}
